#!/usr/bin/env bash
set -euo pipefail

# 提取规则文件中“模块/项目特定”内容到 .tmp/rules_extracted.md（仅收集，不改动原文件）

ROOT_DIR="$(cd "$(dirname "$0")"/.. && pwd)"
SRC_DIR="$ROOT_DIR/rules"
OUT_FILE="$ROOT_DIR/.tmp/rules_extracted.md"

mkdir -p "$ROOT_DIR/.tmp"
echo "# 模块/项目特定内容提取" > "$OUT_FILE"
echo "生成时间：$(date '+%Y-%m-%d %H:%M:%S')" >> "$OUT_FILE"
echo >> "$OUT_FILE"

# 可调整的特定模式（可根据需要扩展）
PATTERNS=(
  'hatchery'
  'example\.company\.project'
  '/api-tests/hatchery'
  '/interface_relations/hatchery'
  'src/test/java/.*/hatchery'
  'MapStructMappings'
  'AIDevFlow'
)

mapfile -t files < <(find "$SRC_DIR" -type f -name "*.md")
for f in "${files[@]}"; do
  local_found=false
  while IFS= read -r line; do
    if [[ -z "$line" ]]; then continue; fi
    for pat in "${PATTERNS[@]}"; do
      if echo "$line" | grep -Eq "$pat"; then
        if [[ "$local_found" == false ]]; then
          echo "## 文件：${f#${ROOT_DIR}/}" >> "$OUT_FILE"
          local_found=true
        fi
        echo "- $line" >> "$OUT_FILE"
        break
      fi
    done
  done < "$f"
done

echo >> "$OUT_FILE"
echo "> 注：以上为收集清单，后续将按占位符 {{...}} 规则进行归位与融合。" >> "$OUT_FILE"
echo "提取完成：$OUT_FILE" >&2
